package com.ls.blog.result;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;


/**
 * @program: myblog
 * @author: lishun
 * @create: 2021-07-05 10:18
 **/


/**
 * 统一返回实体
 * @param <T>
 */
@ToString
@Data
@NoArgsConstructor
public class JsonResult<T> implements Serializable {
    private Boolean success;
    private Integer code;
    private String msg;
    private T data;

    /**
     * 根据是否请求成功返回不带data的结果
     * @param success
     */
    public JsonResult(boolean success) {
        this.success = success;
        this.code = success ? ResultCode.SUCCESS.getCode() : ResultCode.COMMON_FAIL.getCode();
        this.msg = success ? ResultCode.SUCCESS.getMessage() : ResultCode.COMMON_FAIL.getMessage();
    }

    /**
     * 返回其他的失败类型
     * @param success
     * @param resultEnum
     */
    public JsonResult(boolean success, ResultCode resultEnum) {
        this.success = success;
        this.code = success ? ResultCode.SUCCESS.getCode() : (resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode());
        this.msg = success ? ResultCode.SUCCESS.getMessage() : (resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage());
    }

    /**
     * 操作成功
     * @param resultEnum
     */
    public JsonResult(ResultCode resultEnum) {
        this.success = true;
        this.code = resultEnum.getCode();
        this.msg = resultEnum.getMessage();
    }

    public JsonResult(ResultCode resultEnum,T data) {
        this.success = true;
        this.code = resultEnum.getCode();
        this.msg = resultEnum.getMessage();
        this.data=data;
    }

    /**
     * 带数据的默认返回结果
     * @param success
     * @param data
     */
    public JsonResult(boolean success, T data) {
        this.success = success;
        this.code = success ? ResultCode.SUCCESS.getCode() : ResultCode.COMMON_FAIL.getCode();
        this.msg = success ? ResultCode.SUCCESS.getMessage() : ResultCode.COMMON_FAIL.getMessage();
        this.data = data;
    }

    /**
     * 带数据的其他返回结果
     * @param success
     * @param resultEnum
     * @param data
     */
    public JsonResult(boolean success, ResultCode resultEnum, T data) {
        this.success = success;
        this.code = success ? ResultCode.SUCCESS.getCode() : (resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode());
        this.msg = success ? ResultCode.SUCCESS.getMessage() : (resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage());
        this.data = data;
    }
}

